var $ = layui.$;

function usp(obj) {
	var p = new URLSearchParams();
	a: for (let f in obj) {
		let name = f;
		let value = obj[f];
		if (arguments.length > 1) {
			for (let i = 1; i < arguments.length; i += 2) {
				if (arguments[i] == name) {
					if (arguments.length > i + 1) {
						if(! arguments[i + 1]){
							value = null;
							break;
						}
						name = arguments[i] + "." + arguments[i + 1];
						value = eval("obj." + name);
						break;
					} else {
						continue a;
					}
				}
			}
		}
		if (!value || /^\s*$/.test(value)) {
			continue;
		}
		p.append(name, value);
	}
	return p;
}

Date.prototype.format = function(fmt) {
	var o = {
		"M+": this.getMonth() + 1, // 月份
		"d+": this.getDate(), // 日
		"h+": this.getHours(), // 小时
		"m+": this.getMinutes(), // 分
		"s+": this.getSeconds(), // 秒
		"q+": Math.floor((this.getMonth() + 3) / 3), // 季度
		"S": this.getMilliseconds() // 毫秒
	};
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}

function nvl(obj, field, defaultValue) {
	try {
		let ret = obj;
		var arr = field.split(/\./);
		for (let a of arr) {
			ret = ret[a];
		}
		return ret;
	} catch (e) {
		return defaultValue ? defaultValue : '';
	}
}

function param(name) {
	let ret = location.search;
	if (!ret) {
		return "";
	}
	if (name) {
		let regex = new RegExp('[\?&]' + name + '=(.*)[&$]?');
		let res = regex.exec(ret);
		return res && res.length > 1 ? res[1] : '';
	}
	return ret.substring(1);
}

Vue.component('layselect', {
	data() {
		return { id: new Date().getTime(), itemarr: [], modelObj: null, modelName: null };
	},
	props: ['items', 'vf', 'nf', 'model', 'select', 'empty', 'style'],
	template: `<select :lay-filter="'layselect'+id" v-model="modelObj[modelName]" @change="_change" style="border-color:#ddd" :style="style">
					<option v-if="empty" value="" v-text="empty"></option>
					<option v-for="c of itemarr" :value="c[vf||nf||'id']||c">{{c[nf||vf||'name']||c}}</option>
				</select>`,
	created() {
		this.queryItem();
		let _m = this.model ? this.model.split(/\./) : null;
		if (_m) {
			for (let i = 0; i < _m.length; i++) {
				this.modelObj = i == 0 ? this.$parent : this.modelObj[_m[i - 1]];
				this.modelName = _m[i];
			}
		} else {
			this.modelObj = this;
			this.modelName = "select";
		}
		if(this.select){
			this.modelObj[this.modelName] = this.select;
		}
	},
	methods: {
		queryItem() {
			if (typeof this.items == 'string') {
				axios.get(this.items).then(res => {
					this.itemarr = res.data.content || res.data;
				})
			} else {
				this.itemarr = this.items;
			}
		},
		_change() {
			this.$emit("change", this.modelObj[this.modelName]);
		}
	},
	watch: {
		items() {
			this.queryItem();
		}
	},
	updated() {
		layui.form.render();
	},
	mounted() {
		layui.form.render();
		layui.form.on('select(layselect' + this.id + ')', data => {
			this.modelObj[this.modelName] = data.value;
		});
	}
});

Vue.component('intext', {
	props: ['model', 'label'],
	template: `<label style="display:inline-block;margin: 0px 10px">
					<span>{{label}}：</span><input v-model="$parent[model]" style="float:right">
				</label>`
});

Vue.component('load', {
	props: ['url', 'data', 'field', 'join', 'on'],
	created() {
		if (this.join) {
			axios.all([axios.get(this.url), axios.get(this.join)])
				.then(axios.spread((res, res2) => {
					let _d = this.field ? res.data[this.field] : res.data;
					let joindata = res2.data.content ? res2.data.content : res2.data;
					joinData(_d, joindata, this.on);
					eval("this.$parent." + this.data + "=_d;");
					this.$emit("load");
				}));
		} else {
			axios.get(this.url).then(res => {
				let _d = this.field ? res.data[this.field] : res.data;
				let exp;
				if (typeof (_d) == 'object' && Array.isArray(_d) == false) {
					exp = "var _o = this.$parent." + this.data + ";";
					eval(exp);
					// 直接替换对象会使 v-model 失效,  只能一个一个传值
					for (let name in _d) {
						_o[name] = _d[name];
					}
				} else {
					exp = "this.$parent." + this.data + " = _d;";
					eval(exp);
				}
				this.$emit("load");
			});
		}
	}
})

Vue.component('has', {
	data() {
		return { isExists: false };
	},
	props: ['list', 'field', 'value'],
	template: `
		<notag>
			<solt v-if="isExists" name="true"></solt>
			<solt v-else></solt>
		</notag>
	`,
	created() {
		console.info(this.list);
		console.info(this.$parent.logs);
		for (let obj of this.list) {
			eval('let v = obj.' + this.field);
			if (v == this.value) {
				isExists = true;
				return;
			}
		}
	}
})

Vue.component('btn', {
	props: ['url', 'cls'],
	template: `<notag>
					<A v-if="url" :href="url">
						<button :class="'layui-btn layui-btn-sm layui-btn-radius ' + cls"><slot></slot></button>
					</A>
					<button v-else @click='$emit("click")' :class="'layui-btn layui-btn-sm layui-btn-radius ' + cls"><slot></slot></button>
				</notag>`
})

Vue.component('layrdo', {
	data() {
		return { id: increment++, items: [], _m: [] };
	},
	props: ['data', 'model'],
	template: `<notag>
					<input v-if="_m.length==3" v-model="$parent[_m[0]][_m[1]][_m[2]]" v-for="d in items" type="radio" :lay-filter="'layrdo'+id" :name="'layrdo'+id" :value="d.value" :title="d.title">
					<input v-if="_m.length==2" v-model="$parent[_m[0]][_m[1]]" v-for="d in items" type="radio" :lay-filter="'layrdo'+id" :name="'layrdo'+id" :value="d.value" :title="d.title">
					<input v-if="_m.length==1" v-model="$parent[_m[0]]" v-for="d in items" type="radio" :lay-filter="'layrdo'+id" :name="'layrdo'+id" :value="d.value" :title="d.title">
				</notag>`,
	created() {
		if (this.model) {
			this._m = this.model.split(/\./);
		}
		if (typeof (this.data) == 'string') {
			let items = this.data.split(/[,.;，。；:：]+/);
			for (let i = 0; i < items.length; i += 2) {
				if (items[i] != undefined && items[i + 1] != undefined) {
					this.items.push({ title: items[i], value: items[i + 1] });
				}
			}
		}
	},
	updated() {
		layui.form.render();
	},
	mounted() {
		layui.form.render();
		layui.form.on('radio(layrdo' + this.id + ')', data => {
			if (this._m.length == 3) this.$parent[this._m[0]][this._m[1]][this._m[2]] = data.value;
			else if (this._m.length == 2) this.$parent[this._m[0]][this._m[1]] = data.value;
			else if (this._m.length == 1) this.$parent[this._m[0]] = data.value;
		});
	}
})


// 全局自增值，做id用
var increment = 1;
Vue.component('page', {
	data() {
		return { id: 0, laypage: null, pagedata: null, currpage: 1 };
	},
	props: ['url', 'data', 'size', 'join', 'on', 'layout'],
	template: `<div :id="id" style="text-align: center;"></div>`,
	created() {
		this.id = "page" + increment++;
		this.laypage = layui.laypage;
		this.query(this.currpage, true);
	},
	methods: {
		query(page, first) {
			let url = this.url;
			url += this.url.indexOf("?") == -1 ? "?" : "";
			url += '&page=' + page + "&size=" + (this.size || 10);
			if (this.join) {
				let join = this.join;
				join += this.join.indexOf("?") == -1 ? "?" : "";
				// join 必须查询 query 调用SqlDao
				join += '&page:int=' + (page - 1) * (this.size || 10) + "&size:int=" + (this.size || 10);
				let param = { url: url, join: join };
				this.$emit("send", param);
				url = param.url;
				join = param.join;
				axios.all([axios.get(url), axios.get(join)])
					.then(axios.spread((res1, res2) => {
						let joindata = res2.data.content ? res2.data.content : res2.data;
						joinData(res1.data.content, joindata, this.on);
						eval("this.$parent." + this.data + "=res1.data;");
						this.pagedata = res1.data;
						if (first) {
							this.renderPage();
						}
						this.$emit("load");
					}))
			} else {
				let param = { url: url };
				this.$emit("send", param);
				url = param.url;
				axios.get(url).then(res => {
					this.$parent[this.data] = res.data;
					this.pagedata = res.data;
					if (first) {
						this.renderPage();
					}
					this.$emit("load");
				});
			}
		},
		renderPage() {
			//执行一个laypage实例
			this.laypage.render({
				elem: this.id, //注意，这里的 test1 是 ID，不用加 # 号
				limit: this.size,
				layout: this.layout,
				count: this.pagedata.totalElements,//数据总数，从服务端得到
				jump: (obj) => {
					if (this.currpage != obj.curr) {
						this.currpage = obj.curr;
						this.query(obj.curr, false);
					}
				}
			});
		}
	}
});

Vue.component('category',{
	data(){
		return {category:""}
	},
	props: ['data', 'rows', 'cols', 'noempty'],
	template : `
	<div :class="cols?('layui-col-md'+12/cols):'layui-col-md6'" v-if="data&&data.length>0">
   		<div class="category" style="background-color: #eee; margin-top: 5px; border-radius: 5px;overflow: hidden;color:#666">
	   		<div class="title" style="border-bottom: 1px solid #aaa;padding-right: 10px;">
               <span class="left" style="margin:5px 0px;padding:5px;border-left: 4px solid #009688;font-weight:900;">{{data[0].type.name||"技术文章"}}</span>
               <a class="right" :href="'to_category?'+data[0].type.id" style="margin:5px 0px;padding:5px 0px;">更多</a>
               <div style="clear:both"></div>
            </div>
            <ul class="list" style="padding: 10px">
                <li v-for="i of rows?parseInt(rows):10" v-if="data[i-1]!=undefined || noempty==undefined" style="margin-left:7px;padding:5px 0px;border-bottom: 1px dashed #bbb;list-style: disc;height: 16px;">
					<span v-if="data[i-1]!=undefined">
						<a :href="data[i-1].content" target="_blank" @click="read(data[i-1].id)">{{data[i-1].title}}</a>
						<span class="stspan layui-badge layui-bg-orange"
							v-if="new Date().getTime()-parseDate(data[i-1].inTime).getTime()<60*60*1000*24*3">新</span>
					</span>
					<span v-else style="color:#aaa">敬请期待......</span>
					<span v-if="data[i-1]!=undefined" class="right" style='margin-top:3px'>
					<span v-if="data[i-1].readCnt" style="min-width:60px;display:inline-block">访问量:{{data[i-1].readCnt}}</span>
					<span style="min-width:70px;display:inline-block;text-align:right">{{data[i-1].course.name}}</span>
					</span>
                </li>
            </ul>
   		</div>
    </div>
	`,
	methods:{
		read(id){ axios.get("task/article/read?id="+id)}
	}
})

/**
	创建 vue 对象
	参数1： css选择器
	参数2~N：默认创建的data的属性名，默认值是空对象{}
 */
function vue(cssSelector) {
	let _vue = arguments[arguments.length - 1];
	let json = typeof (_vue) == 'object' ? _vue : {};
	json.data = json.data || {};
	json.el = cssSelector;
	for (let i = 1; i < arguments.length; i++) {
		if (arguments[i] && typeof (arguments[i]) == 'string') {
			json.data[arguments[i]] = []; // 创建空数据属性
			json.data[arguments[i]]._temp = null; // 尝试解决vue数据绑定问题
		}
	}
	return new Vue(json);
}

function parseDate(date) {
	if(!date){
		return null;
	} else if (date.constructor.name == 'Date') {
		return date;
	} else if (typeof (date) == 'number') {
		return new Date(date);
	} else if (typeof (date) == 'string') {
		//2021-01-31T03:22:58.000+00:00
		var regex = /(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.(\d+).*/;
		if (regex.exec(date)) {
			return new Date(parseInt(RegExp.$1),
				parseInt(RegExp.$2) - 1,
				parseInt(RegExp.$3),
				parseInt(RegExp.$4),
				parseInt(RegExp.$5),
				parseInt(RegExp.$6),
				parseInt(RegExp.$7));
		}
		regex = /(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})/;
		if (regex.exec(date)) {
			return new Date(parseInt(RegExp.$1),
				parseInt(RegExp.$2) - 1,
				parseInt(RegExp.$3),
				parseInt(RegExp.$4),
				parseInt(RegExp.$5),
				parseInt(RegExp.$6),
				0);
		}
	} else {
		return null;
	}
}

function castDateFormat(datestring, fmt) {
	var date = parseDate(datestring);
	if (date != null) {
		return date.format(fmt || 'yyyy-MM-dd hh:mm:ss');
	} else {
		return '';
	}
}

function alert(msg) {
	for ( let i=1; i<arguments.length; i++){
		if(typeof(arguments[i])=='string') var title = arguments[i];
		else if(arguments[i] <= 6) var anim = arguments[i];
		else if(arguments[i] >100) var time = arguments[i];
	}
	return new Promise(
		function(resolve){
			layer.msg(msg, { 
				title: title || "系统提示", 
				time: time || 3000, 
				anim: anim || 1,
				end(){
					resolve();
				}
			});
		}
	);
}

/**
	id  =  id  ==>  ext
	属性         属性                 新增属性名
 */
function joinData(arr1, arr2, exp) {
	let items = exp.split(/[=>]+/);
	let expstr = "a1." + items[0] + "==" + "a2." + items[1];
	a: for (let a1 of arr1) {
		for (let a2 of arr2) {
			if (eval(expstr) == true) {
				a1[items[2] ? items[2] : 'data'] = a2;
				continue a;
			}
		}
		a1[items[2] ? items[2] : 'data'] = {};
	}
	return arr1;
}

// 截取 html 文本中的 n 个字符和图片,  方法: 先删除除 img 以外所有的标签(反向前瞻+禁止贪婪), 再按数字截取字符串
function charImg(intro, count) {
	let regexp = new RegExp("((<img.+?>|.){0," + count + "}).*");
	let all = intro.replace(/(<(?!img).*?>)/g, '');
	ret = all.replace(regexp, "$1");
	return all.length > ret.length ? (ret + "...") : ret;
}

function lookall(selector, height, subText, allText) {
	if (event.srcElement.innerText == (allText || '显示全部')) {
		document.querySelector(selector).style.maxHeight = '100%';
		event.srcElement.innerText = subText || '收起部分';
	} else {
		document.querySelector(selector).style.maxHeight = height || '300px';
		event.srcElement.innerText = allText || '显示全部';
	}
}

var errMsg = {
	"Missing session attribute 'loginedUser' of type User": "请重新登录系统！"
}
function showErr(res) {
	if (res.status == 200) {
		let result = res.data;
		let es = result.data;
		if (es && es.length) {
			if (es.length == 1) {
				alert("<p style='text-align:left'>" + es[0].defaultMessage + "</p>", result.msg, 3000, 6);
			} else if (es.length > 1) {
				let html = "<ol>";
				for (e of es) {
					html += "<li style='list-style:decimal;text-align:left'>" + e.defaultMessage;
				}
				html += "</ol>";
				alert(html, result.msg, (es.length + 3) * 1000, 6);
			}
		} else {
			alert(result.msg, "系统提示", 3000, 6);
		}
	} else {
		let msg = nvl(res, "response.data.message");
		alert(errMsg[msg] || "系统错误，请联系管理员！", null, 3000, 6);
	}

}

function get(url, param, success, failure) {
	_send("get", url, param, success, failure);
}

function post(url, param, success, failure) {
	_send("post", url, param, success, failure);
}

function _send(method, url, param, success, failure) {
	let $btn = $(window.event.srcElement);
	$btn.addClass("layui-btn-disabled");
	function failureCallback(res) {
		showErr(res);
		if (failure) failure(res);
	}
	let promise;
	if (method == "get") {
		promise = axios.get(url, param);
	} else if (method == "post") {
		promise = axios.post(url, param);
	}
	promise.then(res => {
		if (res.data.code == 1) {
			if (success) success(res);
		} else {
			failureCallback(res);
		}
		$btn.removeClass("layui-btn-disabled");
	}, res => {
		failureCallback(res);
		$btn.removeClass("layui-btn-disabled");
	});
}

function getCookie(name) {
	let reg = new RegExp(".*\\b" + name + "\\b=([\\w\\-]+).*");
	if (reg.test(document.cookie)) {
		return document.cookie.replace(reg, "$1");
	} else {
		return "";
	}
}

function replace(str){
	for(let i=1; i<arguments.length; i++){
		let reg = new RegExp("\\["+i+"\\]","g");
		str = str.replace(reg,arguments[i]);
	}
	return str;
}

